#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
库存管理模块
负责库存监控和管理
"""

import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime
import random

class InventoryManager:
    def __init__(self, data_manager):
        self.data_manager = data_manager
        
    def create_ui(self, parent):
        """创建库存管理界面"""
        # 主框架
        main_frame = tk.Frame(parent, bg='white')
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 标题
        title_label = tk.Label(main_frame, text="库存管理", 
                              font=('微软雅黑', 16, 'bold'),
                              bg='white', fg='#2c3e50')
        title_label.pack(pady=10)
        
        # 创建上下分割的界面
        # 上半部分：库存预警和统计
        top_frame = tk.Frame(main_frame, bg='white')
        top_frame.pack(fill='x', pady=10)
        
        # 库存预警
        warning_frame = tk.LabelFrame(top_frame, text="库存预警", 
                                     font=('微软雅黑', 12, 'bold'),
                                     bg='white', fg='#e74c3c')
        warning_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        self.warning_text = tk.Text(warning_frame, height=6, width=40,
                                   font=('微软雅黑', 9),
                                   bg='#fff5f5', fg='#e74c3c',
                                   relief='flat', wrap='word')
        self.warning_text.pack(padx=10, pady=10, fill='both', expand=True)
        
        # 库存统计
        stats_frame = tk.LabelFrame(top_frame, text="库存统计", 
                                   font=('微软雅黑', 12, 'bold'),
                                   bg='white', fg='#27ae60')
        stats_frame.pack(side='right', fill='both', expand=True, padx=(10, 0))
        
        self.stats_text = tk.Text(stats_frame, height=6, width=40,
                                 font=('微软雅黑', 9),
                                 bg='#f8fff8', fg='#27ae60',
                                 relief='flat', wrap='word')
        self.stats_text.pack(padx=10, pady=10, fill='both', expand=True)
        
        # 下半部分：库存列表和操作
        bottom_frame = tk.Frame(main_frame, bg='white')
        bottom_frame.pack(fill='both', expand=True, pady=10)
        
        # 操作按钮框架
        button_frame = tk.Frame(bottom_frame, bg='white')
        button_frame.pack(fill='x', pady=10)
        
        tk.Button(button_frame, text="新增商品", 
                 command=self.add_item_dialog,
                 font=('微软雅黑', 10),
                 bg='#27ae60', fg='white',
                 width=12).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="修改商品", 
                 command=self.edit_item_dialog,
                 font=('微软雅黑', 10),
                 bg='#3498db', fg='white',
                 width=12).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="删除商品", 
                 command=self.delete_item,
                 font=('微软雅黑', 10),
                 bg='#e74c3c', fg='white',
                 width=12).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="入库操作", 
                 command=self.stock_in_dialog,
                 font=('微软雅黑', 10),
                 bg='#f39c12', fg='white',
                 width=12).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="出库操作", 
                 command=self.stock_out_dialog,
                 font=('微软雅黑', 10),
                 bg='#9b59b6', fg='white',
                 width=12).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="刷新数据", 
                 command=self.refresh_data,
                 font=('微软雅黑', 10),
                 bg='#95a5a6', fg='white',
                 width=12).pack(side='left', padx=5)
        
        # 搜索和筛选框架
        search_frame = tk.Frame(bottom_frame, bg='white')
        search_frame.pack(fill='x', pady=10)
        
        tk.Label(search_frame, text="搜索:", font=('微软雅黑', 10),
                bg='white').pack(side='left', padx=5)
        
        self.search_var = tk.StringVar()
        search_entry = tk.Entry(search_frame, textvariable=self.search_var,
                               font=('微软雅黑', 10), width=20)
        search_entry.pack(side='left', padx=5)
        search_entry.bind('<KeyRelease>', self.on_search)
        
        # 分类筛选
        tk.Label(search_frame, text="分类:", font=('微软雅黑', 10),
                bg='white').pack(side='left', padx=(20, 5))
        
        self.category_var = tk.StringVar(value="全部")
        categories = ["全部", "蔬菜", "肉类", "海鲜", "主食", "调料"]
        category_combo = ttk.Combobox(search_frame, textvariable=self.category_var,
                                     values=categories, width=10, state="readonly")
        category_combo.pack(side='left', padx=5)
        category_combo.bind('<<ComboboxSelected>>', self.on_search)
        
        # 库存状态筛选
        tk.Label(search_frame, text="库存状态:", font=('微软雅黑', 10),
                bg='white').pack(side='left', padx=(20, 5))
        
        self.stock_status_var = tk.StringVar(value="全部")
        status_combo = ttk.Combobox(search_frame, textvariable=self.stock_status_var,
                                   values=["全部", "正常", "库存不足", "库存充足"],
                                   width=12, state="readonly")
        status_combo.pack(side='left', padx=5)
        status_combo.bind('<<ComboboxSelected>>', self.on_search)
        
        # 库存列表框架
        list_frame = tk.Frame(bottom_frame, bg='white')
        list_frame.pack(fill='both', expand=True, pady=10)
        
        # 创建Treeview
        columns = ("商品编号", "商品名称", "分类", "单位", "当前库存", "最小库存", "最大库存", "单价", "仓库", "状态")
        self.tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题和宽度
        column_widths = [100, 120, 80, 60, 80, 80, 80, 80, 100, 80]
        for i, (col, width) in enumerate(zip(columns, column_widths)):
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width, anchor='center')
        
        # 滚动条
        scrollbar_y = ttk.Scrollbar(list_frame, orient='vertical', command=self.tree.yview)
        scrollbar_x = ttk.Scrollbar(list_frame, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
        
        # 布局
        self.tree.pack(side='left', fill='both', expand=True)
        scrollbar_y.pack(side='right', fill='y')
        scrollbar_x.pack(side='bottom', fill='x')
        
        # 加载数据
        self.refresh_data()
        
    def refresh_data(self):
        """刷新所有数据"""
        self.update_warnings()
        self.update_statistics()
        self.refresh_inventory_list()
        
    def update_warnings(self):
        """更新库存预警信息"""
        self.warning_text.delete(1.0, tk.END)
        
        low_stock_items = self.data_manager.get_low_stock_items()
        
        if not low_stock_items:
            self.warning_text.insert(tk.END, "✅ 当前没有库存不足的商品")
        else:
            self.warning_text.insert(tk.END, f"⚠️ 发现 {len(low_stock_items)} 个商品库存不足：\n\n")
            
            for item in low_stock_items:
                warning_msg = f"• {item['name']}\n"
                warning_msg += f"  当前库存: {item['current_stock']} {item['unit']}\n"
                warning_msg += f"  最小库存: {item['min_stock']} {item['unit']}\n"
                warning_msg += f"  建议补货: {item['max_stock'] - item['current_stock']} {item['unit']}\n\n"
                self.warning_text.insert(tk.END, warning_msg)
        
        self.warning_text.config(state='disabled')
        
    def update_statistics(self):
        """更新库存统计信息"""
        self.stats_text.delete(1.0, tk.END)
        
        items = self.data_manager.get_inventory_items()
        warehouses = {w["id"]: w["name"] for w in self.data_manager.get_warehouses()}
        
        if not items:
            self.stats_text.insert(tk.END, "暂无库存数据")
            return
        
        # 基本统计
        total_items = len(items)
        total_value = sum(item['current_stock'] * item['unit_price'] for item in items)
        low_stock_count = len(self.data_manager.get_low_stock_items())
        
        stats_msg = f"📊 库存统计概览\n\n"
        stats_msg += f"商品种类总数: {total_items}\n"
        stats_msg += f"库存总价值: ¥{total_value:,.2f}\n"
        stats_msg += f"库存不足商品: {low_stock_count}\n\n"
        
        # 分类统计
        category_stats = {}
        for item in items:
            category = item['category']
            if category not in category_stats:
                category_stats[category] = {'count': 0, 'value': 0}
            category_stats[category]['count'] += 1
            category_stats[category]['value'] += item['current_stock'] * item['unit_price']
        
        stats_msg += "📋 分类统计:\n"
        for category, stats in category_stats.items():
            stats_msg += f"• {category}: {stats['count']}种 (¥{stats['value']:,.2f})\n"
        
        self.stats_text.insert(tk.END, stats_msg)
        self.stats_text.config(state='disabled')
        
    def refresh_inventory_list(self):
        """刷新库存列表"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 获取数据
        items = self.data_manager.get_inventory_items()
        warehouses = {w["id"]: w["name"] for w in self.data_manager.get_warehouses()}
        
        # 应用搜索和筛选
        search_text = self.search_var.get().lower()
        category_filter = self.category_var.get()
        status_filter = self.stock_status_var.get()
        
        for item in items:
            # 搜索筛选
            if search_text and search_text not in item["name"].lower():
                continue
                
            # 分类筛选
            if category_filter != "全部" and item["category"] != category_filter:
                continue
            
            # 库存状态判断
            if item["current_stock"] <= item["min_stock"]:
                stock_status = "库存不足"
                status_color = "#e74c3c"
            elif item["current_stock"] >= item["max_stock"] * 0.8:
                stock_status = "库存充足"
                status_color = "#27ae60"
            else:
                stock_status = "正常"
                status_color = "#3498db"
                
            # 状态筛选
            if status_filter != "全部" and stock_status != status_filter:
                continue
                
            warehouse_name = warehouses.get(item["warehouse_id"], "未知仓库")
            
            item_id = self.tree.insert('', 'end', values=(
                item["id"],
                item["name"],
                item["category"],
                item["unit"],
                item["current_stock"],
                item["min_stock"],
                item["max_stock"],
                f"¥{item['unit_price']:.2f}",
                warehouse_name,
                stock_status
            ))
            
            # 根据库存状态设置行颜色
            if stock_status == "库存不足":
                self.tree.set(item_id, "状态", "⚠️ 库存不足")
            elif stock_status == "库存充足":
                self.tree.set(item_id, "状态", "✅ 库存充足")
            else:
                self.tree.set(item_id, "状态", "📦 正常")
                
    def on_search(self, event=None):
        """搜索事件处理"""
        self.refresh_inventory_list()
        
    def add_item_dialog(self):
        """新增商品对话框"""
        dialog = tk.Toplevel()
        dialog.title("新增库存商品")
        dialog.geometry("500x700")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 商品编号（自动生成）
        row = 0
        tk.Label(form_frame, text="商品编号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        item_id = f"ITEM{str(len(self.data_manager.get_inventory_items()) + 1).zfill(3)}"
        tk.Label(form_frame, text=item_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品名称
        row += 1
        tk.Label(form_frame, text="商品名称:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        name_var = tk.StringVar()
        name_entry = tk.Entry(form_frame, textvariable=name_var,
                             font=('微软雅黑', 10), width=25)
        name_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 分类
        row += 1
        tk.Label(form_frame, text="分类:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        category_var = tk.StringVar()
        categories = ["蔬菜", "肉类", "海鲜", "主食", "调料"]
        category_combo = ttk.Combobox(form_frame, textvariable=category_var,
                                     values=categories, width=22, state="readonly")
        category_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单位
        row += 1
        tk.Label(form_frame, text="单位:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        unit_var = tk.StringVar()
        units = ["公斤", "克", "个", "瓶", "包", "箱"]
        unit_combo = ttk.Combobox(form_frame, textvariable=unit_var,
                                 values=units, width=22, state="readonly")
        unit_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 当前库存
        row += 1
        tk.Label(form_frame, text="当前库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        current_stock_var = tk.StringVar()
        current_stock_entry = tk.Entry(form_frame, textvariable=current_stock_var,
                                      font=('微软雅黑', 10), width=25)
        current_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 最小库存
        row += 1
        tk.Label(form_frame, text="最小库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        min_stock_var = tk.StringVar()
        min_stock_entry = tk.Entry(form_frame, textvariable=min_stock_var,
                                  font=('微软雅黑', 10), width=25)
        min_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 最大库存
        row += 1
        tk.Label(form_frame, text="最大库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        max_stock_var = tk.StringVar()
        max_stock_entry = tk.Entry(form_frame, textvariable=max_stock_var,
                                  font=('微软雅黑', 10), width=25)
        max_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单价
        row += 1
        tk.Label(form_frame, text="单价:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        unit_price_var = tk.StringVar()
        unit_price_entry = tk.Entry(form_frame, textvariable=unit_price_var,
                                   font=('微软雅黑', 10), width=25)
        unit_price_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 供应商
        row += 1
        tk.Label(form_frame, text="供应商:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        supplier_var = tk.StringVar()
        suppliers = self.data_manager.get_suppliers()
        supplier_names = [f"{s['name']} ({s['id']})" for s in suppliers]
        supplier_combo = ttk.Combobox(form_frame, textvariable=supplier_var,
                                     values=supplier_names, width=22, state="readonly")
        supplier_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 仓库
        row += 1
        tk.Label(form_frame, text="仓库:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        warehouse_var = tk.StringVar()
        warehouses = self.data_manager.get_warehouses()
        warehouse_names = [f"{w['name']} ({w['id']})" for w in warehouses]
        warehouse_combo = ttk.Combobox(form_frame, textvariable=warehouse_var,
                                      values=warehouse_names, width=22, state="readonly")
        warehouse_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def save_item():
            try:
                # 验证输入
                if not all([name_var.get(), category_var.get(), unit_var.get(),
                           current_stock_var.get(), min_stock_var.get(), max_stock_var.get(),
                           unit_price_var.get(), supplier_var.get(), warehouse_var.get()]):
                    messagebox.showerror("错误", "请填写所有必填字段")
                    return
                
                # 获取供应商和仓库ID
                supplier_id = supplier_var.get().split('(')[1].split(')')[0]
                warehouse_id = warehouse_var.get().split('(')[1].split(')')[0]
                
                # 创建商品
                item = {
                    "id": item_id,
                    "name": name_var.get(),
                    "category": category_var.get(),
                    "unit": unit_var.get(),
                    "current_stock": int(current_stock_var.get()),
                    "min_stock": int(min_stock_var.get()),
                    "max_stock": int(max_stock_var.get()),
                    "unit_price": float(unit_price_var.get()),
                    "supplier_id": supplier_id,
                    "warehouse_id": warehouse_id
                }
                
                # 保存商品
                self.data_manager.add_inventory_item(item)
                messagebox.showinfo("成功", "商品已添加")
                dialog.destroy()
                self.refresh_data()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=save_item,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def edit_item_dialog(self):
        """修改商品对话框"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要修改的商品")
            return
            
        # 获取选中的商品
        item = self.tree.item(selected[0])
        item_id = item['values'][0]
        
        # 找到对应的商品数据
        items = self.data_manager.get_inventory_items()
        current_item = None
        for inv_item in items:
            if inv_item['id'] == item_id:
                current_item = inv_item
                break
                
        if not current_item:
            messagebox.showerror("错误", "未找到商品数据")
            return
        
        # 创建修改对话框（类似新增对话框，但预填充数据）
        dialog = tk.Toplevel()
        dialog.title("修改库存商品")
        dialog.geometry("500x700")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 商品编号（只读）
        row = 0
        tk.Label(form_frame, text="商品编号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        tk.Label(form_frame, text=item_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品名称
        row += 1
        tk.Label(form_frame, text="商品名称:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        name_var = tk.StringVar(value=current_item['name'])
        name_entry = tk.Entry(form_frame, textvariable=name_var,
                             font=('微软雅黑', 10), width=25)
        name_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 分类
        row += 1
        tk.Label(form_frame, text="分类:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        category_var = tk.StringVar(value=current_item['category'])
        categories = ["蔬菜", "肉类", "海鲜", "主食", "调料"]
        category_combo = ttk.Combobox(form_frame, textvariable=category_var,
                                     values=categories, width=22, state="readonly")
        category_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单位
        row += 1
        tk.Label(form_frame, text="单位:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        unit_var = tk.StringVar(value=current_item['unit'])
        units = ["公斤", "克", "个", "瓶", "包", "箱"]
        unit_combo = ttk.Combobox(form_frame, textvariable=unit_var,
                                 values=units, width=22, state="readonly")
        unit_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 当前库存
        row += 1
        tk.Label(form_frame, text="当前库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        current_stock_var = tk.StringVar(value=str(current_item['current_stock']))
        current_stock_entry = tk.Entry(form_frame, textvariable=current_stock_var,
                                      font=('微软雅黑', 10), width=25)
        current_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 最小库存
        row += 1
        tk.Label(form_frame, text="最小库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        min_stock_var = tk.StringVar(value=str(current_item['min_stock']))
        min_stock_entry = tk.Entry(form_frame, textvariable=min_stock_var,
                                  font=('微软雅黑', 10), width=25)
        min_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 最大库存
        row += 1
        tk.Label(form_frame, text="最大库存:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        max_stock_var = tk.StringVar(value=str(current_item['max_stock']))
        max_stock_entry = tk.Entry(form_frame, textvariable=max_stock_var,
                                  font=('微软雅黑', 10), width=25)
        max_stock_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单价
        row += 1
        tk.Label(form_frame, text="单价:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        unit_price_var = tk.StringVar(value=str(current_item['unit_price']))
        unit_price_entry = tk.Entry(form_frame, textvariable=unit_price_var,
                                   font=('微软雅黑', 10), width=25)
        unit_price_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 供应商
        row += 1
        tk.Label(form_frame, text="供应商:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        supplier_var = tk.StringVar()
        suppliers = self.data_manager.get_suppliers()
        supplier_names = [f"{s['name']} ({s['id']})" for s in suppliers]
        
        # 设置当前供应商
        current_supplier = None
        for s in suppliers:
            if s['id'] == current_item['supplier_id']:
                current_supplier = f"{s['name']} ({s['id']})"
                break
        supplier_var.set(current_supplier or "")
        
        supplier_combo = ttk.Combobox(form_frame, textvariable=supplier_var,
                                     values=supplier_names, width=22, state="readonly")
        supplier_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 仓库
        row += 1
        tk.Label(form_frame, text="仓库:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        warehouse_var = tk.StringVar()
        warehouses = self.data_manager.get_warehouses()
        warehouse_names = [f"{w['name']} ({w['id']})" for w in warehouses]
        
        # 设置当前仓库
        current_warehouse = None
        for w in warehouses:
            if w['id'] == current_item['warehouse_id']:
                current_warehouse = f"{w['name']} ({w['id']})"
                break
        warehouse_var.set(current_warehouse or "")
        
        warehouse_combo = ttk.Combobox(form_frame, textvariable=warehouse_var,
                                      values=warehouse_names, width=22, state="readonly")
        warehouse_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def update_item():
            try:
                # 验证输入
                if not all([name_var.get(), category_var.get(), unit_var.get(),
                           current_stock_var.get(), min_stock_var.get(), max_stock_var.get(),
                           unit_price_var.get(), supplier_var.get(), warehouse_var.get()]):
                    messagebox.showerror("错误", "请填写所有必填字段")
                    return
                
                # 获取供应商和仓库ID
                supplier_id = supplier_var.get().split('(')[1].split(')')[0]
                warehouse_id = warehouse_var.get().split('(')[1].split(')')[0]
                
                # 更新商品
                updated_item = current_item.copy()
                updated_item.update({
                    "name": name_var.get(),
                    "category": category_var.get(),
                    "unit": unit_var.get(),
                    "current_stock": int(current_stock_var.get()),
                    "min_stock": int(min_stock_var.get()),
                    "max_stock": int(max_stock_var.get()),
                    "unit_price": float(unit_price_var.get()),
                    "supplier_id": supplier_id,
                    "warehouse_id": warehouse_id
                })
                
                # 保存更新
                self.data_manager.update_inventory_item(item_id, updated_item)
                messagebox.showinfo("成功", "商品已更新")
                dialog.destroy()
                self.refresh_data()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"更新失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=update_item,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def delete_item(self):
        """删除商品"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要删除的商品")
            return
            
        # 获取选中的商品
        item = self.tree.item(selected[0])
        item_id = item['values'][0]
        item_name = item['values'][1]
        
        if messagebox.askyesno("确认", f"确定要删除商品 {item_name} 吗？"):
            self.data_manager.delete_inventory_item(item_id)
            messagebox.showinfo("成功", "商品已删除")
            self.refresh_data()
            
    def stock_in_dialog(self):
        """入库操作对话框"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要入库的商品")
            return
            
        # 获取选中的商品
        item = self.tree.item(selected[0])
        item_id = item['values'][0]
        item_name = item['values'][1]
        current_stock = int(item['values'][4])
        
        dialog = tk.Toplevel()
        dialog.title(f"入库操作 - {item_name}")
        dialog.geometry("400x300")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        tk.Label(form_frame, text=f"商品: {item_name}", 
                font=('微软雅黑', 12, 'bold'),
                bg='white').pack(pady=10)
        
        tk.Label(form_frame, text=f"当前库存: {current_stock}", 
                font=('微软雅黑', 10),
                bg='white').pack(pady=5)
        
        tk.Label(form_frame, text="入库数量:", 
                font=('微软雅黑', 10),
                bg='white').pack(pady=10)
        
        quantity_var = tk.StringVar()
        quantity_entry = tk.Entry(form_frame, textvariable=quantity_var,
                                 font=('微软雅黑', 12), width=20,
                                 justify='center')
        quantity_entry.pack(pady=5)
        quantity_entry.focus()
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.pack(pady=20)
        
        def confirm_stock_in():
            try:
                if not quantity_var.get() or not quantity_var.get().isdigit():
                    messagebox.showerror("错误", "请输入有效的数量")
                    return
                
                quantity = int(quantity_var.get())
                if quantity <= 0:
                    messagebox.showerror("错误", "入库数量必须大于0")
                    return
                
                # 更新库存
                items = self.data_manager.get_inventory_items()
                for inv_item in items:
                    if inv_item['id'] == item_id:
                        inv_item['current_stock'] += quantity
                        self.data_manager.update_inventory_item(item_id, inv_item)
                        break
                
                messagebox.showinfo("成功", f"已入库 {quantity} 单位，当前库存: {current_stock + quantity}")
                dialog.destroy()
                self.refresh_data()
                
            except Exception as e:
                messagebox.showerror("错误", f"入库失败: {str(e)}")
        
        tk.Button(button_frame, text="确认入库", command=confirm_stock_in,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=12).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=12).pack(side='left', padx=10)
        
    def stock_out_dialog(self):
        """出库操作对话框"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要出库的商品")
            return
            
        # 获取选中的商品
        item = self.tree.item(selected[0])
        item_id = item['values'][0]
        item_name = item['values'][1]
        current_stock = int(item['values'][4])
        
        dialog = tk.Toplevel()
        dialog.title(f"出库操作 - {item_name}")
        dialog.geometry("400x300")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        tk.Label(form_frame, text=f"商品: {item_name}", 
                font=('微软雅黑', 12, 'bold'),
                bg='white').pack(pady=10)
        
        tk.Label(form_frame, text=f"当前库存: {current_stock}", 
                font=('微软雅黑', 10),
                bg='white').pack(pady=5)
        
        tk.Label(form_frame, text="出库数量:", 
                font=('微软雅黑', 10),
                bg='white').pack(pady=10)
        
        quantity_var = tk.StringVar()
        quantity_entry = tk.Entry(form_frame, textvariable=quantity_var,
                                 font=('微软雅黑', 12), width=20,
                                 justify='center')
        quantity_entry.pack(pady=5)
        quantity_entry.focus()
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.pack(pady=20)
        
        def confirm_stock_out():
            try:
                if not quantity_var.get() or not quantity_var.get().isdigit():
                    messagebox.showerror("错误", "请输入有效的数量")
                    return
                
                quantity = int(quantity_var.get())
                if quantity <= 0:
                    messagebox.showerror("错误", "出库数量必须大于0")
                    return
                
                if quantity > current_stock:
                    messagebox.showerror("错误", "出库数量不能大于当前库存")
                    return
                
                # 更新库存
                items = self.data_manager.get_inventory_items()
                for inv_item in items:
                    if inv_item['id'] == item_id:
                        inv_item['current_stock'] -= quantity
                        self.data_manager.update_inventory_item(item_id, inv_item)
                        break
                
                new_stock = current_stock - quantity
                messagebox.showinfo("成功", f"已出库 {quantity} 单位，当前库存: {new_stock}")
                dialog.destroy()
                self.refresh_data()
                
            except Exception as e:
                messagebox.showerror("错误", f"出库失败: {str(e)}")
        
        tk.Button(button_frame, text="确认出库", command=confirm_stock_out,
                 font=('微软雅黑', 10), bg='#e74c3c', fg='white',
                 width=12).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=12).pack(side='left', padx=10) 